const app = getApp()
var QQMapWX = require('../../qqmap-wx-jssdk.js');
const db = wx.cloud.database({
  env: 'cloud1-2g6vpgs796710242'
})
var qqmapsdk = new QQMapWX({
  key: '5KLBZ-G7ZKP-5Y7D3-V7CUF-MLZW5-LBFQ5'
});

var record_user_list = []

Page({
  data: {
    chooseava: "",
    situation: true,
    key: "",
    planet: false,
    sider: false,
    show: false,
    duration: 300,
    position: 'right',
    round: true,
    overlay: true,
    customStyle: '',
    overlayStyle: '',
    startX: 0,
    startY: 0,
    direction: null,
    latitude: '',
    longitude: '',
    today: '',
    city: null,
    cp: [],
    userID:"",
    management:[],
    hasUserInfo: false,
    userInfo:[],
    user_list: [],
    rec_user: [],
    gender:"--",
    search_term:[],
    aimCP:"",
    um:"",
    common:[{"count":0,"name":"Venus","icon":"https://636c-cloud1-2g6vpgs796710242-1304238103.tcb.qcloud.la/Mars.png?sign=1ce437c783290fd4c7763c3025a7f6be&t=1679039017","pid":"987a453763f8d49a01da795b172637c1"},
            {"count":0,"name":"Uranus","icon":"https://636c-cloud1-2g6vpgs796710242-1304238103.tcb.qcloud.la/Mercury.png?sign=b73d37fe54f78d161741bd412da2700b&t=1679038988","pid":"1db297d463f4b369015d122e74dbcbf0"},
            {"count":0,"name":"Neptune","icon":"https://636c-cloud1-2g6vpgs796710242-1304238103.tcb.qcloud.la/Neptune.png?sign=2cedc82c985f8b8710242de8b90ef6e0&t=1679038942","pid":"9ca5b13363f4b064000ada6424b897c7"},
            {"count":0,"name":"Trending*","icon":"https://636c-cloud1-2g6vpgs796710242-1304238103.tcb.qcloud.la/%E6%8E%92%E8%A1%8C%E6%A6%9C.png?sign=89de460f37f076bfdbda0b1e88e16ec5&t=1678610933","pid":"2cc84e26640d91ea0413edee04f88c60"},
            {"count":0,"name":"Conference*","icon":"https://636c-cloud1-2g6vpgs796710242-1304238103.tcb.qcloud.la/%E4%BC%9A%E8%AE%AE.png?sign=754edb439bde68f3d4f4f728fd8ed951&t=1678610599","pid":"0122a587640d9095040f64bc4e41faaf"},
            {"count":0,"name":"Polestar","icon":"https://636c-cloud1-2g6vpgs796710242-1304238103.tcb.qcloud.la/%E5%A4%87%E7%94%A82.png?sign=55e98b55fc2c41c910a47a6c5a1b8959&t=1681116859","pid":"e1bf55d86433cea6000423826041d87f"}
          ],
    ftrack:[],
    uinfo:[]
  },

  onLoad: function () {
    app.getOpenid()  //全局获取openid
    this.getOpenid()  //获取当前用户openid
    this.get_Btweet() //获取活动运营位推文
    // this.getUserLocation()
    this.getWeather() //获取天气信息
    // 获取功能库中的信息
    db.collection('cp_list')
    .get()
    .then(res=>{
      console.log(res)
      this.setData({
        cp:res.data
      })
    })
    .catch(err=>{
      console.log("行星库数据获取失败",err)
    })
    //获取用户数据集
    db.collection('User')
    .get()
    .then(res => {
      console.log("用户列表", res)
      res.data.forEach(Element=>{
        record_user_list.push(Element.openid)
      })
      this.setData({
        user_list: res.data,
        rec_user: record_user_list
      })
      console.log("全局数组中", record_user_list)
      setTimeout(() => {
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i]._openid == app.globalData.openid) {
            console.log("全局openid catchUserinfo",app.globalData.openid)
            app.globalData.ulevel = res.data[i].level
            var that = this
            that.setData({
              hasUserInfo:true,
              chooseava:res.data[i].avatarUrl,
              um:res.data[i].nickName
            })
            console.log("type+ava",this.data.hasUserInfo,this.data.chooseava)
            wx.setStorage({
              key:'user', 
              data:{"ava":res.data[i].avatarUrl,"name":res.data[i].nickName},
            })
          }
        }
        //获取用户信息缓存
        wx.getStorage({
          key:'user',
          success: (res)=> {
            console.log("缓存",res.data)
            app.globalData.ava = res.data.ava
            this.setData({
              hasUserInfo: true,
              chooseava:res.data.ava
            })
          },
          fail: (err)=> {
            console.log("无缓存用户信息",err)
            wx.showToast({
              title: '部分功能需要授权登入才能正常使用',
              icon: "none"
            })
          }
        })
      }, 1700);
    })
    .catch(err => {
      console.log("获取失败", err)
    })
  },

  onChooseAvatar(e) {
    console.log("授权信息",e)
    var userhs = e.detail.avatarUrl
    this.setData({
      chooseava: userhs,
      hasUserInfo:true
    })
    wx.cloud.uploadFile({
      cloudPath: '用户头像'+app.globalData.openid+'.png',
      url: 'https://example.weixin.qq.com/upload', //仅为示例，非真实的接口地址
      filePath: userhs,
      success: (res)=>{
        console.log("上传成功",res)
        app.globalData.ava = res.fileID
        wx.setStorage({
          key:'user', 
          data:{"ava":res.fileID,"name":"你的名字"},
        })
        // 上传用户信息至数据库
        db.collection("User").add({
          data: {
            "avatarUrl": res.fileID,
            "nickName": "填写名字",
            "common": this.data.common,
            "level":0,
            "organization":""
          },
          success(res) {
            console.log("添加成功", res)
          },
          fail(res) {
            console.log("添加失败", res)
          },
        })
      },
      fail: (err)=>{
        console.log("上传失败",err)
      },
    })
  },

  //客服
  handleContact (e) {
    console.log(e.detail.path)
    console.log(e.detail.query)
  },

  // 获取当前位置经纬度
  getWeather: function () {
    var that = this;
    wx.authorize({
      scope: 'scope.userFuzzyLocation',
      success: function(res) {
        console.log(res)
        if(res.errMsg == 'authorize:ok'){
          wx.getFuzzyLocation({
            type: "gcj02",
            success: function (res) {
              console.log("经纬度",res)
              that.setData({
                latitude: res.latitude,
                longitude: res.longitude
              })
              console.log(res);
              that.getWeatherInfo()
            },
            fail: (err) => {
              console.log(err)
            }
          });
        }
      },
      fail(err) {
        console.log(err)   
      }                    
    })
  },

  /**天气 */
  getWeatherInfo: function () {
    var that = this;
    var key = '3a7be72f2cfc4d0f972a80b1cc581628';
    console.log("that.data.longitude",that.data.longitude)
    console.log("that.data.latitude",that.data.latitude)
    var url = 'https://devapi.qweather.com/v7/weather/now?key=' + key + '&location=' + that.data.longitude + ',' + that.data.latitude;
    wx.request({
      url: url,
      data: {},
      method: 'GET',
      success: function (res) {
        console.log(res);
        var daily_forecast_today = res.data.now;//今天天气
        console.log("daily_forecast_today", res.data.now.obsTime.slice(0, 10))
        that.setData({
          today: daily_forecast_today,
          date:res.data.now.obsTime.slice(0, 10)
        });
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: that.data.latitude,
            longitude: that.data.longitude
          },
          success: function(res) {//成功后的回调
            console.log(res.result.ad_info.city);
            that.setData({
              city: res.result.ad_info.city
            })
            },
          fail: function(error) {
            console.error(error);
          },
          complete: function(res) {
            console.log(res);
          }
        })
      }
    })
  },



  display(event) {
    //---------------------remember to limit the null value----------------------
    var key = event.detail.value
    this.setData({
      key: key
    })
    console.log(this.data.key)
  },

  baidu() {
    wx.request({
      header: {
        "content-type": "application/json",
      },
      method: "GET",
      url: "https://xueshu.baidu.com/usercenter/data/paperreco?cmd=batch_get_kw_chart&kw_list="+this.data.key+"&_token=fc55526ac7bb6e3ab419fe69e594a13130b3c2679074fc620eeb6745dc6aa422&_ts=1641370793&_sign=718e5448c7838507e1615c1dd7d60081",
      success: res => {
        console.log("成功", res.data);
        var originData = res.data
        var bat = encodeURIComponent(JSON.stringify(res.data))
        db.collection("Rank")
        //变量查询需要加上[]
        .where({
          type:"keyword",
          name: this.data.key
        })
        .get()
        .then(res=>{
          console.log("关键词查重",res)
          this.setData({
            search_term:res.data
          })
          if (res.data.length==0 || res.data==null) {
            db.collection("Rank")
            .add({
              data:{
                name:this.data.key,
                count:1,
                type:"keyword",
                time:new Date().toJSON().substring(0, 10)
              }
            }).then(res=>{
              console.log("add_kw",res)
            })
            .catch(err=>{
              console.log("add_wrong",err)
            })
          } else {
            db.collection("Rank")
            .where({
              type:"keyword",
              name:this.data.key
            }).update({
              data:{
                time:new Date().toJSON().substring(0, 10),
                count:this.data.search_term[0].count+1
              }
            })
            .then(res=>{
              console.log("update_kw",res)
            })
            .catch(err=>{
              console.log("update_wrong",err)
            })
          }
        })
        .catch(err=>{
          console.log(err)
        })
        var datalength = res.data.data.length
        var iffail = originData.message.indexOf("fail")
        if (datalength==0) {
          wx.showToast({ title: '无相关数据结果', icon: 'none' });
        } else if (iffail>=0) {
          wx.showToast({ title: '不支持该词汇检索', icon: 'none' });
        } else {
          wx.navigateTo({
            url: '../output1/output1?baidu=' + bat
          })
        }
      },
      fail: err => {
        console.log("错误", err);
      }
    })
  },

  search() {
    if (this.data.key !== '') {
      wx.request({
        header: {
          "content-type": "application/json",
        },
        method: "POST",
        url: "http://www.eling.asia",
        data: {
          code: this.data.key
        },
        success: res => {
          console.log("成功", res.data);
          var bat = JSON.stringify(res.data)
          db.collection("Rank")
          //变量查询需要加上[]
          .where({
            type:"keyword",
            name: this.data.key
          })
          .get()
          .then(res=>{
            console.log("关键词查重",res)
            this.setData({
              search_term:res.data
            })
            if (res.data.length==0 || res.data==null) {
              db.collection("Rank")
              .add({
                data:{
                  name:this.data.key,
                  count:1,
                  type:"keyword",
                  time:new Date().toJSON().substring(0, 10)
                }
              }).then(res=>{
                console.log("add_kw",res)
              })
              .catch(err=>{
                console.log("add_wrong",err)
              })
            } else {
              db.collection("Rank")
              .where({
                type:"keyword",
                name:this.data.key
              }).update({
                data:{
                  time:new Date().toJSON().substring(0, 10),
                  count:this.data.search_term[0].count+1
                }
              })
              .then(res=>{
                console.log("update_kw",res)
              })
              .catch(err=>{
                console.log("update_wrong",err)
              })
            }
          })
          .catch(err=>{
            console.log(err)
          })
          console.log("结果长度",res.data.data.length)
          if (res.data.data.length==0) {
            wx.showToast({ title: '无相关数据结果', icon: 'none' });
          } else {
            wx.navigateTo({
              url: '../output1/output1?baidu=' + bat
            })
          }
        },
        fail: err => {
          console.log("错误", err);
        }
      })
    } else {
      wx.showToast({ title: '请输入关键词', icon: 'none' });
    }
  },

  //拉起弹窗
  pop_cabinet(e) {
    console.log("拉起仓储",e)
    var cpid = e.currentTarget.dataset.id
    this.setData({
      aimCP:cpid
    })
    const position = "bottom"
    let customStyle = ''
    let duration = this.data.duration
    switch (position) {
      case 'top':
      case 'bottom':
        customStyle = 'height: 20%;'
        break
      case 'right':
        break
    }
    this.setData({
      position,
      show: true,
      customStyle,
      duration
    })
  },

  changelamp() {
    //切换画面
    if (this.data.situation==true) {
      this.setData({
        situation:false,
        show: false
      })
    } else if (this.data.situation==false) {
      this.setData({
        situation:true,
        sider:false
      })
    }
  },

  clickplanet() {
    this.setData({
      planet: true
    })
  },

  touchstart: function (e) {
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY
    })
  },

  //滑动中判断滑动方向
  touchmove: function (e) {
    let startX = this.data.startX // 开始x坐标
    let startY = this.data.startY // 开始y坐标
    let touchMoveX = e.changedTouches[0].clientX // 活动变化坐标
    let touchMoveY = e.changedTouches[0].clientY //滑动变化坐标
    let angle = this.angle({
      X: startX,
      Y: startY
    }, {
      X: touchMoveX,
      Y: touchMoveY
    })
    //滑动角度超过45retrun
    console.log(Math.abs(angle), "Math.abs(angle)")
    if (Math.abs(angle) > 45) return
    if (touchMoveX > startX) { //右滑
      this.setData({
        direction: 'R'
      })
    } else {
      this.setData({ //左滑
        direction: 'L'
      })
    }
  },

  // 滑动角度限制
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 / Math,atan()返回数据的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI)
  },

  // 滑动结束
  tochend: function (e) {
    let that = this
    if (this.data.direction == 'R') { // 左滑相当于上一页
      console.log("左滑")
    } else if (this.data.direction == 'L') { //右滑相当于下一页
      console.log("右滑")
      that.setData({
        sider: true
      })
    } else { // 相当于滑动不成立,清空driection
      this.setData({
        direction: ''
      })
    }
  },

  To_planet: function (e) {
    var pid = e.currentTarget.dataset.id
    if (pid=="9ca5b13363f4b064000ada6424b897c7") {
      wx.navigateTo({
        url: '../planet/planet?id=' + pid,
      })
    }
    if (pid=="1db297d463f4b369015d122e74dbcbf0") {
      wx.navigateTo({
        url: '../planetM/planetM?id=' + pid,
      })
    }
    if (pid=="987a453763f8d49a01da795b172637c1") {
      wx.navigateTo({
        url: '../planetM2/planetM2?id=' + pid,
      })
    }
    if (pid=="0122a587640d9095040f64bc4e41faaf") {
      wx.navigateTo({
        url: '../socials/socials?id=' + pid
      })
    }
    if (pid=="2cc84e26640d91ea0413edee04f88c60") {
      wx.navigateTo({
        url: '../rank/rank?id=' + pid
      })
    }
    if (pid=="e1bf55d86433cea6000423826041d87f") {
      wx.navigateTo({
        url: '../lib/lib?id=' + pid
      })
    }
    else {
      console.log("无id")
    }
  },

  onShareAppMessage: function () {
    return {
      title: 'Bibliauthor',
      imageUrl: ''
    }
  },

  onShow() {
    record_user_list.splice(0, record_user_list.length)
    // if (user) {
    //   console.log('用户信息已授权',user)
    //   this.setData({
    //     hasUserInfo: true,
    //     userInfo: user,
    //   })
    //   console.log("用户信息", this.data.userInfo)
    // } else {
    //   console.log("无缓存用户信息")
    //   this.get_Profile()
    // }
  },

  getOpenid() {
    console.log("getOpenid")
    wx.cloud.callFunction({
      config:{ env: 'cloud1-2g6vpgs796710242' },
      name:"Get_useropenid"
    }).then(res=>{
      console.log("获取openid成功",res.result.event.userInfo.openId)
      this.setData({
        userID:res.result.event.userInfo.openId
      })
      this.get_common()
    }).catch(err=>{
      console.log("获取失败",err)
    })
  },

  review() {
    wx.navigateTo({
      url: '../history/history?openid=' + this.data.userID
    })
  },

  playtricks() {
    wx.navigateTo({
      url: '../handbook/handbook'
    })
  },

  work() {
    wx.navigateTo({
      url: '../Mywork/Mywork'
    })
  },

  get_Btweet() {
    db.collection("Management")
    .get()
    .then(res=>{
      console.log("platform信息",res)
      this.setData({
        management:res.data[0]
      })
    })
    .catch(err=>{
      console.log("获取失败",err)
    })
  },

  go_tweet(e) {
    var tlink = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: '/pages/tweet/tweet?url=' + tlink,
    })
  },

  //接口已弃用
  // get_Profile() {
  //   wx.getUserProfile({
  //     lang: 'zh_CN',
  //     desc: '用于完善会员资料',
  //     success: (res) => {
  //       console.log("用户信息", res.userInfo)
  //       this.setData({
  //         userInfo: res.userInfo,
  //         hasUserInfo: true
  //       })
  //       wx.showToast({
  //         title: '授权成功',
  //       })
  //       wx.setStorage({
  //         key:'user', 
  //         data:res.userInfo
  //       })
  //       this.store_user_info(res)
  //     }
  //   })
  // },

  store_user_info() {
    wx.setStorage({
      key:'user', 
      data:{"ava":this.data.chooseava,"name":this.data.um},
    })
    console.log("openid",this.data.userID)
    console.log("判断openid是否在用户列表中", record_user_list.indexOf(this.data.userID))
    var judge_store = record_user_list.indexOf(this.data.openid)
    if (judge_store > -1) {
      db.collection("User").where({
          _openid: this.data.userID
        })
        .update({
          data: {
            "avatarUrl": this.data.chooseava,
            "nickName": this.data.um,
          }
        })
        .then(res => {
          console.log("更新成功", res)
          wx.showToast({
            title: '更新成功',
          })
        })
        .catch(err => {
          console.log("更新失败", err)
        })
    } else {
      db.collection("User").add({
        data: {
          "avatarUrl": app.globalData.ava,
          "nickName": this.data.um,
          "common":this.data.common,
          "level":0,
          "organization":""
        },
        success(res) {
          console.log("添加成功", res)
          wx.showToast({
            title: '更新成功',
          })
        },
        fail(res) {
          console.log("添加失败", res)
        },
      })
    }
  },

  userName(e) {
    var um = e.detail.value
    this.setData({
      um: um
    })
    console.log(this.data.um)
  },

  get_common() {
    db.collection("User")
    .where({
      _openid:this.data.userID
    })
    .get()
    .then(res=>{
      console.log("用户数据",res.data[0])
      var clist = res.data[0].common
      var compare = function (prop) {
        return function (obj1, obj2) {
            var val1 = obj1[prop];
            var val2 = obj2[prop];if (val1 < val2) {
                return -1;
            } else if (val1 > val2) {
                return 1;
            } else {
                return 0;
            }            
        } 
      }
      console.log("排序结果",clist.sort(compare("count")).reverse())
      this.setData({
        ftrack:res.data[0].common
      })
    })
    .catch(err=>{
      console.log(err)
    })
  },

  go_home() {
    wx.navigateTo({
      url: '../village/village',
    })
  },

  getUserLocation: function () {
    var _this=this
    wx.getSetting({
      success (res) {
        console.log("位置信息授权结果",res.authSetting)//会返回用户授权的结果
    //scope.userLocation参数表示的是地理位置授权状态 
    // undefined-初始化进入该页面/false-非初始化进入该页面,且未授权/true-地理位置授权
      let locationStatus=res.authSetting['scope.userLocation']
         if (locationStatus != undefined && locationStatus != true) {
              //未授权
              wx.showModal({
                title: '请求授权当前位置',
                content: '需要获取您的地理位置，请确认授权',
                success: function (res) {
                  if (res.cancel) {
                    //取消授权
                    wx.showToast({
                      title: '拒绝授权',
                      icon: 'none',
                      duration: 1000
                    })
                  } else if (res.confirm) {
                    //用户拒接授权后，通过wx.openSetting重新发起授权请求
                    wx.openSetting({
                      success: function (res) {
                        if (locationStatus == true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          _this.getWeather();
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'none',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            } else if (locationStatus == undefined) {
              _this.getWeather();
            } else {
              console.log('授权成功')
              _this.getWeather();
            }
      }
    })
  }
  
})